<template>
	<div class="sys-region-container">
		<el-dialog v-model="state.isShowDialog" draggable :close-on-click-modal="false" width="700px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>
					<span> {{ props.title }} </span>
				</div>
			</template>

			<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24"class="mb20">
				<el-form-item label="基础数据上传" prop="name" :rules="[{ required: true, message: '管理处名称不能为空', trigger: 'blur' }]">
				</el-form-item>
			</el-col>
			<el-col :span="12" class="mb20">
				<el-form-item label="" prop="baseInfo">
					<template #default>
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(100)" > 上传路网基础信息 (必须先上传)</el-button> <br>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.baseInfo"   @click="downloadFile(state.baseInfosrc)" >已入库 | 路网基础信息下载 </el-button>
					</template>
				</el-form-item>
			</el-col>

			<el-col :span="12" class="mb20">
				<el-form-item label="" prop="hjsj">
					<template #default>
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(101)" >上传环境数据 </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.hjsj"   @click="downloadFile(state.hjsjsrc)" >已入库 | 环境数据下载 </el-button>
																																							
					</template>
				</el-form-item>
			</el-col>

			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
				<el-form-item label="" prop="jtl">
					<template #default>
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(102)" >上传交通量数据   </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.jtl"   @click="downloadFile(state.jtlsrc)" >已入库 | 交通量下载 </el-button>

					</template>
				</el-form-item>
			</el-col>
			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
				<el-form-item label="" prop="sxp">
					<template #default>
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(103)" >上传上下坡数据 </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.sxp"   @click="downloadFile(state.sxpsrc)" >已入库 | 上下坡下载 </el-button>

					</template>
				</el-form-item>
			</el-col>
			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
				<el-form-item label="" prop="lmjg">
					<template #default>
						<el-button icon="ele-Edit" size="small" text type="primary"    @click="openUploadDialog(104)" >上传路面结构数据 </el-button>
						<el-button icon="ele-Download" size="small" text type="primary"    v-if="state.lmjg"   @click="downloadFile(state.lmjgsrc)" >已入库 | 路面结构下载 </el-button>

					</template>
				</el-form-item>
			</el-col>

			<!--	<MapDragRoute ref="mapDragRoute" :title="地图组件" @handleQuery="handleQuery"  :regionData="state.regionData"/>-->

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="uploadState.dialogUploadVisible" :lock-scroll="false" draggable width="400px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-UploadFilled /> </el-icon>
					<span> 上传文件 </span>
				</div>
			</template>
			<div>
				<el-upload ref="uploadRef" drag :auto-upload="false" :limit="5" :file-list="uploadState.fileList" action="" :on-change="handleChange" accept=".jpg,.png,.bmp,.gif,.txt,.pdf,.xlsx,.docx">
					<el-icon class="el-icon--upload">
						<ele-UploadFilled />
					</el-icon>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<template #tip>
						<div class="el-upload__tip">请上传大小不超过 10MB 的文件</div>
					</template>
				</el-upload>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="uploadState.dialogUploadVisible = false">取消</el-button>
					<el-button type="primary" @click="uploadFile">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<WarmPrompt
			v-model:visible="showPrompt"
			message="当前商户号暂不存在入驻90天且连续交易30天"
			@confirm="handlePromptConfirm"
			@cancel="handlePromptCancel"
		/>
	</div>
</template>

<script lang="ts" setup name="sysEditRegion">
import { reactive, ref } from 'vue';
import {ElMessage, UploadInstance} from 'element-plus';
import { getAPI } from '/@/utils/axios-utils';
import {SysRegionApi} from '/@/api-services/api';
import {SysFile} from '/@/api-services/models';
import {uploadFilesPoject} from "/@/api/region/region";
import { downloadByUrl } from '/@/utils/download';

interface Props {
	title: string
	row: Record<string, any>
	regionData: any[]
	year: string
	pid: string
}

const props = withDefaults(defineProps<Props>(), {
	title: '',
	row: () => ({}),
	regionData: () => [],
	year: '',
	pid: ''
})

interface Emits {
	(e: 'handleQuery'): void
}

const emit = defineEmits<Emits>()

const ruleFormRef = ref();
const ruleForm = ref<any>({});
const uploadRef = ref<UploadInstance>();

// 定义 state 的接口
interface State {
	fileData: Array<SysFile>
	selectedOption: string
	isShowDialog: boolean
	baseInfo: string
	baseInfosrc: string
	hjsj: string
	hjsjsrc: string
	jtl: string
	jtlsrc: string
	sxp: string
	sxpsrc: string
	lmjg: string
	lmjgsrc: string
	lmjzinfo: string
	lmjzinfosrc: string
	jcce: string
	jccesrc: string
	jcjspd: string
	jcjspdsrc: string
	jcpss: string
	jcpsssrc: string
	jcpsx: string
	jcpsxsrc: string
	jcpzd: string
	jcpzdsrc: string
	fileName: string
	pdfUrl: string
	docxUrl: string
	excelUrl: string
	dialogPdfVisible: boolean
	dialogDocxVisible: boolean
	dialogXlsxVisible: boolean
	previewList: string[]
	showViewer: boolean
	showPrompt: boolean
	Pid: number
}

// 修改 state 的定义
const state = reactive<State>({
	fileData: [],
	selectedOption: "",
	isShowDialog: false,
	baseInfo: '',
	baseInfosrc: '',
	hjsj: '',
	hjsjsrc: '',
	jtl: '',
	jtlsrc: '',
	sxp: '',
	sxpsrc: '',
	lmjg: '',
	lmjgsrc: '',
	lmjzinfo: '',
	lmjzinfosrc: '',
	jcce: '',
	jccesrc: '',
	jcjspd: '',
	jcjspdsrc: '',
	jcpss: '',
	jcpsssrc: '',
	jcpsx: '',
	jcpsxsrc: '',
	jcpzd: '',
	jcpzdsrc: '',
	fileName: '',
	pdfUrl: '',
	docxUrl: '',
	excelUrl: '',
	dialogPdfVisible: false,
	dialogDocxVisible: false,
	dialogXlsxVisible: false,
	previewList: [],
	showViewer: false,
	showPrompt: false,
	Pid: 0
})

// 修改 uploadState 的类型
interface UploadState {
	dialogUploadVisible: boolean
	fileList: any[]
	key: number
	year: string | number | undefined
}

const uploadState = reactive<UploadState>({
	dialogUploadVisible: false,
	fileList: [],
	key: 0,
	year: undefined,
})

// 打开上传页面
const openUploadDialog = (key: any)=> {
	uploadState.fileList = [];
	uploadState.key=key;
	if(props.year) {
		// 如果 props.year 有值，则使用 props.year
		uploadState.year = props.year;
	} else {
		// 如果 props.year 为 null 或 undefined，则设置默认的当前时间年度
		const currentDate = new Date();
		uploadState.year = currentDate.getFullYear()
	}
	console.log('传递过来参数属性',props.row)
	uploadState.dialogUploadVisible = true;

};

// 下载
const downloadFile = async (url: any) => {
	downloadByUrl({ url: url });
};

// 打开文件预览页面
const openFilePreviewDialog = async (row: any) => {
	if (row.suffix == '.pdf') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.pdfUrl = getFileUrl(row);
		state.dialogPdfVisible = true;
	} else if (row.suffix == '.docx') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.docxUrl = getFileUrl(row);
		state.dialogDocxVisible = true;
	} else if (row.suffix == '.xlsx') {
		state.fileName = `【${row.fileName}${row.suffix}】`;
		state.excelUrl = getFileUrl(row);
		state.dialogXlsxVisible = true;
	} else if (['.jpg', '.png', '.jpeg', '.bmp'].findIndex((e) => e == row.suffix) > -1) {
		state.previewList = [getFileUrl(row)];
		state.showViewer = true;
	} else {
		ElMessage.error('此文件格式不支持预览');
	}
};


// 获取文件地址
const getFileUrl = (row: SysFile): string => {
	if (row.bucketName == 'Local') {
		return `/${row.filePath}/${row.id}${row.suffix}`;
	} else {
		return row.url!;
	}
};

// 通过onChanne方法获得文件列表
const handleChange = (file: any, fileList: []) => {
	uploadState.fileList = fileList;
};



// 上传
const uploadFile = async () => {
	const params = new FormData()
	
	if (uploadState.fileList.length >= 1) {
		for (const file of uploadState.fileList) {
			params.append('files', file.raw)
		}
		params.append('year', String(uploadState.year))
		params.append('key', String(uploadState.key))
		
		const fileInfoResponse = await uploadFilesPoject(params)
		handleFileInfoResponse(fileInfoResponse)
		if(fileInfoResponse.data.type === 'success') {
			ElMessage.success('上传成功')
			uploadState.dialogUploadVisible = false
		}
	}
	uploadState.key = 0
	state.Pid = 0
	uploadState.dialogUploadVisible = false
}

// 添加 fileInfoResponse 的类型
interface FileInfoResponse {
	data: {
		type: string
		result: Array<{
			id: string
			url: string
		}>
	}
}

const handleFileInfoResponse = (fileInfoResponse: FileInfoResponse) => {
	// 根据 key 值进行判断和赋值
	console.log('key', uploadState.key);

	switch (uploadState.key) {
		case 100:
			state.baseInfo = fileInfoResponse.data.result[0].id;
			state.baseInfosrc = fileInfoResponse.data.result[0].url;
			console.log('基础信息excl', state.baseInfosrc );
			break;
		case 2:
			state.jcce = fileInfoResponse.data.result[0].id;
			state.jccesrc = fileInfoResponse.data.result[0].url;
			break;
		case 3:
			state.jcjspd = fileInfoResponse.data.result[0].id;
			state.jcjspdsrc = fileInfoResponse.data.result[0].url;
			break;
		case 4:
			state.jcpss = fileInfoResponse.data.result[0].id;
			state.jcpsssrc = fileInfoResponse.data.result[0].url;
			break;
		case 5:
			state.jcpsx = fileInfoResponse.data.result[0].id;
			state.jcpsxsrc = fileInfoResponse.data.result[0].url;
			break;
		default:
			break;
	}
};


// 打开弹窗
const openDialog = async () => {
	console.log('Saving with pid:', props.pid);
	// ruleForm.value = JSON.parse(JSON.stringify(row));
	// 改用detail获取最新数据来编辑
	state.isShowDialog = true;


	//	state.leidaimage = ruleForm.value.leidaimage;
	//	state.leidaimagesrc = ruleForm.value.leidaimagesrc;

};

// 关闭弹窗
const closeDialog = () => {
	emit('handleQuery');
	state.isShowDialog = false;

};

// 取消
const cancel = () => {
	uploadState.fileList = [];
	state.isShowDialog = false;
};

// 提交
const submit = async () => {
	try {
		const isValid = await ruleFormRef.value.validate()
		if (!isValid) return
		
		const values = {
			...ruleForm.value,
			pid: props.pid,
			year: props.year,
			jcpzd: state.jcpzd,
			jcpzdsrc: state.jcpzdsrc,
			leidaimage: state.lmjzinfo,
			leidaimagesrc: state.lmjzinfosrc
		}

		if (!values.id) {
			await getAPI(SysRegionApi).apiSysRegionAddPost(values)
		} else {
			await getAPI(SysRegionApi).apiSysRegionUpdatePost(values)
		}
		
		closeDialog()
		ElMessage.success('操作成功')
	} catch (error) {
		ElMessage.error('操作失败')
		console.error(error)
	}
}

// 文件渲染完成
const renderedHandler = () => {};
// 文件渲染失败
const errorHandler = () => {};
// 导出对象
defineExpose({ openDialog });

const handlePromptConfirm = () => {
	// 处理确认逻辑
	state.showPrompt = false
}

const handlePromptCancel = () => {
	// 处理取消逻辑
	state.showPrompt = false
}

// 建议将文件上传逻辑抽离为独立的 composable
const useFileUpload = () => {
	const uploadFile = async (files: File[], year: string, key: number) => {
		const params = new FormData()
		files.forEach(file => params.append('files', file))
		params.append('year', year)
		params.append('key', key.toString())
		
		try {
			const response = await uploadFilesPoject(params)
			return response
		} catch (error) {
			ElMessage.error('上传失败')
			throw error
		}
	}

	return {
		uploadFile
	}
}

// 使用
const { uploadFile: uploadFileFromComposable } = useFileUpload()
</script>

